package com.mind.servlet;

import com.mind.common.config.MindConfig;
import com.mind.common.utils.StringUtils;
import com.mind.common.utils.file.MimeTypeUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.util.IOUtils;
import org.apache.tika.Tika;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriUtils;

import java.io.*;
import java.net.URLEncoder;

/**
 * @author today
 * @version 2025年3月25日 09:21:44
 */
@WebServlet(urlPatterns = "/customer/file/*")
public class UserFilesDownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(getClass());

	public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String prefix = "/customer/file/";
		String filepath = req.getRequestURI();
		int index = filepath.indexOf(prefix);
		if(index >= 0) {
			filepath = filepath.substring(index + prefix.length());
		}

		filepath = UriUtils.decode(filepath, "UTF-8");
		File file = new File(MindConfig.getUploadPath() + filepath);
		try{
			exportFile(file,resp,req);
		}catch (Exception e){
			e.printStackTrace();
		}

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fileOutputStream(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fileOutputStream(req, resp);
	}
	public void exportFile(File downloadFile, HttpServletResponse response,HttpServletRequest request) {
		try{
			response.setHeader("Content-Disposition" ,"inline;filename="+downloadFile.getName());
			Tika tika = new Tika();
			String contentType = tika.detect(downloadFile);
			logger.info(contentType);
			response.setContentType(contentType);
			ServletOutputStream outputStream = response.getOutputStream();
			InputStream in = new FileInputStream(downloadFile);// 读取文件
			long i = IOUtils.copy(in, outputStream);   // copy流数据,i为字节数
			in.close();
			outputStream.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

}
